package com.zhangjk.sign.controller;

import com.zhangjk.sign.test.SignService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sign/server")
public class SignServerController {

    /**
     * 1.公钥库
     * 2.目前测试,真实环境下，取自数据库(redis、mysql)
     * 3.公钥必须唯一，根据 公钥 取数据中 私钥 。
     *
     */
    private static List<String> secretKeyList= Arrays.asList("mysecret123456","123113cczzzxx");


    /**
     * 模拟服务的API接口
     * @param request
     * @return
     */
    @PostMapping("checkSign")
    public String checkSign(HttpServletRequest request){
        //从request中获取参数列表，转成map
        Map<String, String> map = SignService.toVerifyMap(request.getParameterMap(),false);
        String secretKey =  map.get("secretKey");



        if (StringUtils.isEmpty(secretKey) || !getSecretKey(map.get("secretKey"))){
            System.out.println("secretKey is err");
            return "fail";
        }
        if (SignService.verify(map)){
            return "success";
        }else {
            return "fail";
        }
    }

    private Boolean getSecretKey(String param){
        for (String secretKey: secretKeyList){
            if(param.equals(secretKey)){
                return true;
            }
        }
      return false;
    }


}
